# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,reverse,redirect
from  .forms import RegisterForm
from .models import *
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.

def register(request):
    if request.method == 'POST':
        user_form = RegisterForm(request.POST,request.FILES)
        if user_form.is_valid():
            userq = User.objects.filter(username=user_form.cleaned_data['username'])

            if userq:
                register_form = RegisterForm()
                return render(request, 'register.html', {'reg': register_form,'error':'账户已存在'})
            else:
                user = User(username=user_form.cleaned_data['username'],password=user_form.cleaned_data['password'],img=request.FILES['img'])
                user.save()
                response = HttpResponseRedirect('/question/login/')
                return response
        else:
            register_form = RegisterForm()
            return render(request, 'register.html', {'reg': register_form,'error':'验证没成功'})
    else:
         register_form = RegisterForm()
         return render(request,'register.html',{'reg':register_form})
def login(request):
    if request.method == 'POST':
        username = request.POST['name']
        password = request.POST['password']
        user = User.objects.filter(username=username,password=password)
        if user:
            response = HttpResponseRedirect('/question/index/')
            response.set_cookie('username',username)
            return response
        else:
            c = {'error':'账户或密码错误'}
            return render(request,template_name='login.html',context= c)
    else:
        return render(request,'login.html')
def index(request):
    questions = Question.objects.all().order_by('-datetime')
    # questions = question[::-1]
    paginator = Paginator(questions,5)
    page = request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.page(paginator.num_pages)
    cook = request.COOKIES.get('username')
    return render(request,'index.html',{'cook':cook,'posts':post_list})


def question(request):
    if request.method == 'POST':
        title = request.POST['title']
        content = request.POST['post']
        print content
        classify = request.POST['tags']
        cid = Classify.objects.filter(classify=classify).first()
        # print uid.id
        cook = request.COOKIES.get('username')
        uid = User.objects.filter(username=cook).first()
        # print cid.id

        question = Question(title=title,content=content,u_id=uid,c_id=cid)
        question.save()
        return HttpResponseRedirect('/question/index')
    else:
        classify = Classify.objects.all()
        cook = request.COOKIES.get('username')
        return render(request,'ask.html',{'cook':cook,'classify':classify})

def reply(request,question_id):
    if request.method == 'POST':
        rep_content = request.POST['post']
        question = Question.objects.filter(id=question_id).first()
        cook = request.COOKIES.get('username')
        u_id = User.objects.filter(username=cook).first()
        rep = Reply(rep_content=rep_content,u_id=u_id,q_id=question)
        rep.save()
        return HttpResponseRedirect(reverse('questions:reply',args=[question_id]))

    else:
        rep = Reply.objects.filter(q_id=question_id)
        cook = request.COOKIES.get('username')
        classify = Classify.objects.all()
        question = Question.objects.filter(id=question_id).first()

        return render(request,'answer.html',{'question':question,'cook':cook,'rep':rep,'classify':classify})